<?php
	/**
		Page that pulls chat information for ajax call to update chat text box
		
		@author Joseph Fehrman
	*/
	$username = $_COOKIE['username'];
	$chatRoom = $_POST['chat_room'];
	$chatLastUpdate = $_POST['last_updated'];
	$maxPing = 5;
	include_once("../db/connection.php");
	
	function loadIt($chatRoom, $oldUpdate, $conn, $num, $maxPing){
	//Query that pulls information from chatRoom
		$currentChatText = "";
		$sqlGetChatText = "Select chat_text, last_updated from chat where id='$chatRoom'";
		$results = mysqli_query($conn, $sqlGetChatText) OR die("Error on query: " . $sqlGetChatText);
		$lastUpdated;
		while ($row = mysqli_fetch_array($results, MYSQL_BOTH)){
			$currentChatText = $row['chat_text'];
			$lastUpdated = $row['last_updated'];
		}
		if(($oldUpdate != $lastUpdated) || ($num >= $maxPing)){
			echo $currentChatText . ", " . $lastUpdated;
			return true;
		}else{
			return false;
		}
	}
	
	$i = 0;
	$isDone = false;
	while(($i < $maxPing) && (!$isDone)){
		$isDone = loadIt($chatRoom, $chatLastUpdate, $conn, $i, $maxPing);
		$i++;
		sleep(1);
		if($isDone){
			$i = $maxPing;
		}
	}
	//Returns the current content of chatRoom
	//echo $currentChatText ", " + $lastUpdated;
	mysqli_close($conn);
?>